package com.atos.howl.chaos.web.controller.login;

import com.atos.howl.chaos.enums.ChaosSysCodeEnum;
import com.atos.howl.chaos.pdm.dto.ChaosRegistryDTO;
import com.atos.howl.chaos.pdm.dto.login.LoginResultDTO;
import com.atos.howl.chaos.pdm.entity.User;
import com.atos.howl.chaos.pdm.mapper.UserMapper;
import com.atos.howl.chaos.pdm.service.LoginService;
import com.atos.howl.chaos.pdm.service.UserService;
import com.atos.howl.chaos.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;


@Controller
@RequestMapping("/api/loginController")
public class LoginController {

//    @Resource
//    //private UserMapper userMapper;
    @Autowired
    private LoginService loginService;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @ResponseBody
    public LoginResultDTO login(@RequestBody @Valid User user){
        boolean isAccountExist = loginService.isAccountExist(user);
        LoginResultDTO result = new LoginResultDTO();

        if(isAccountExist)
        {
            //通过account查找uuid
            user.setUserUuid(userService.getUUIDByAccount(user.getAccount()));
            //登陆成功,添加状态码
            result.setChaosCode(ChaosSysCodeEnum.SUCCESS.getChaosCode());
            result.setChaosCodeDesc(ChaosSysCodeEnum.SUCCESS.getChaosCodeDesc());
            //使用账号和uuid以及token生成器生成一个token
            String chaosToken = TokenUtils.sign(user.getAccount(),user.getUserUuid());
            result.setChaosToken(chaosToken);
        }

        if(!isAccountExist)
        {
            //登陆失败，也添加状态码
            result.setChaosCode(ChaosSysCodeEnum.ERROR01.getChaosCode());
            result.setChaosCodeDesc(ChaosSysCodeEnum.ERROR01.getChaosCodeDesc());
        }



        //result.setLoginSuccess(isAccountExist);
        return result;
    }
}
